package com.ihunanren.biz.function.service.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.ihunanren.biz.common.HnrResourceLoader;
import com.ihunanren.biz.function.Http;
import com.ihunanren.biz.function.domain.Weather;
import com.ihunanren.biz.function.domain.Weatherinfo;
import com.ihunanren.biz.function.service.IWeixinService;
import com.ihunanren.common.CollectionUtils;

public class WeatherService implements IWeixinService<Weatherinfo>,InitializingBean{

	private final static Logger log = LoggerFactory.getLogger(WeatherService.class);
	private String fileName = "wx_weather_city.dat";
	private boolean initSuccess = false;

	private Map<Long, String> divisionMap = null;
	
	@Override
	public List<Weatherinfo> getResponse(String input) {
		checkArgument(!isNullOrEmpty(input));

		String url = genarateUrl(input);
		if (isNullOrEmpty(url)) {
			return null;
		}

		Http http = new Http();
		String json = http.doGetAsString(url, null);
		Weather weather = JSON.parseObject(json, Weather.class);
		return Arrays.asList(weather.getWeatherinfo());
	}
	
	private String genarateUrl(String divisionName){
		long id = -1;
		if(CollectionUtils.isEmpty(divisionMap)){
			destoryDivision();
			initDivision();
		}
		for(Map.Entry<Long, String> entry : divisionMap.entrySet()){
			String value = entry.getValue();
			if (divisionName.indexOf(value) >= 0) {
				id = entry.getKey().longValue();
				break;
			}
		}
		if(id < 0)return null;
		
		StringBuilder sb = new StringBuilder();
		sb.append("http://m.weather.com.cn/data/").append(id).append(".html");
		return sb.toString();
	}
	

	@Override
	public void afterPropertiesSet() throws Exception {
		if (!initSuccess) {
			initDivision();
		}
	}

	private void destoryDivision(){
		divisionMap = null;
		initSuccess = false;
	}
	
	private void initDivision() {
		BufferedReader reader = null;
		try {
			divisionMap = Maps.newHashMap();
			InputStream inputStream = HnrResourceLoader.getResoureceAsInputStream(fileName);
			reader = new BufferedReader(new InputStreamReader(inputStream));
			
			String line = null;
			while ((line = reader.readLine()) != null) { // 读取配置文件格式：编号=地区名称
				String[] tmparray = line.split("=", 2);
				if(tmparray != null && tmparray.length ==2){
					divisionMap.put(new Long(tmparray[0]), tmparray[1]);
				}
			}
			initSuccess = true;
		} catch (Exception e) {
			log.error("initDivision catch a exception.", e);
			Throwables.propagate(e);
		}
	}
	
}
